<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="预案名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入预案名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['biz:emgPlan:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['biz:emgPlan:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['biz:emgPlan:remove']"
              >删除</el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['biz:emgPlan:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="emgPlanDetailList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="false" />
        <el-table-column label="预案名称" align="center" prop="name" />
        <el-table-column label="附件" align="center" prop="file">
          <template #default="scope">
            <file-upload v-model="scope.row.file" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="isEnable">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.isEnable" />
          </template>
        </el-table-column>
        <el-table-column label="责任部门" align="center" prop="deptInCharge" />
        <el-table-column label="责任人" align="center" prop="contacts" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:emgPlan:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:emgPlan:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改应急预案详情对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="emgPlanDetailFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="预案名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入预案名称" />
        </el-form-item>
        <el-form-item label="附件编号" prop="file">
          <file-upload v-model="form.file" :limit="1" :fileType="['pdf']" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnable">
          <el-switch v-model="form.isEnable" active-value="0" inactive-value="1" />
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="分级信息" prop="levelDetail">
              <el-table :data="levelDetailData">
                <el-table-column prop="levelName" label="级别名称">
                  <template #default="{ row, $index }">
                    <div v-if="editableRowIndex === $index && editableColumn === 'levelName'">
                      <el-select v-model="row.levelName" @blur="saveEdit(row)" @keyup.enter="saveEdit(row)">
                        <el-option value="I级" label="I级" />
                        <el-option value="II级" label="II级" />
                        <el-option value="III级" label="III级" />
                        <el-option value="IIII级" label="IIII级" />
                        <el-option value="V级" label="V级" />
                      </el-select>
                    </div>
                    <div v-else @click="startEdit($index, 'levelName')">
                      {{ row.levelName || '-' }}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="deadNum" label="死亡人数">
                  <template #default="{ row, $index }">
                    <div v-if="editableRowIndex === $index && editableColumn === 'deadNum'">
                      <el-input v-model="row.deadNum" @blur="saveEdit(row)" @keyup.enter="saveEdit(row)" />
                    </div>
                    <div v-else @click="startEdit($index, 'deadNum')" style="width: 100%">
                      {{ row.deadNum || '-' }}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="injuredNum" label="或重伤人数">
                  <template #default="{ row, $index }">
                    <div v-if="editableRowIndex === $index && editableColumn === 'injuredNum'">
                      <el-input v-model="row.injuredNum" @blur="saveEdit(row)" @keyup.enter="saveEdit(row)" />
                    </div>
                    <div v-else @click="startEdit($index, 'injuredNum')" style="width: 100%">
                      {{ row.injuredNum || '-' }}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="economicLoss" label="或经济损失">
                  <template #default="{ row, $index }">
                    <div v-if="editableRowIndex === $index && editableColumn === 'economicLoss'">
                      <el-input v-model="row.economicLoss" @blur="saveEdit(row)" @keyup.enter="saveEdit(row)" />
                    </div>
                    <div v-else @click="startEdit($index, 'economicLoss')" style="width: 100%">
                      {{ row.economicLoss || '-' }}
                    </div>
                  </template>
                </el-table-column>
                <!-- 操作列 -->
                <el-table-column label="操作" width="80px">
                  <template #default="{ $index }">
                    <el-button type="danger" size="small" @click="deleteRow($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 新增行按钮 -->
              <el-button type="primary" @click="addRow" style="margin-top: 16px">新增一行</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任部门" prop="deptInCharge">
              <el-input v-model="form.deptInCharge" placeholder="请输入责任部门" />
            </el-form-item>
            <el-form-item label="责任人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人和联系方式" />
            </el-form-item>
            <el-form-item label="工作内容">
              <el-input v-model="form.workContent" type="textarea" placeholder="请输入工作内容" :rows="6" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EmgPlanDetail" lang="ts">
import { listEmgPlanDetail, getEmgPlanDetail, delEmgPlanDetail, addEmgPlanDetail, updateEmgPlanDetail } from '@/api/biz/emgPlanDetail';
import { EmgPlanDetailVO, EmgPlanDetailQuery, EmgPlanDetailForm } from '@/api/biz/emgPlanDetail/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const emgPlanDetailList = ref<EmgPlanDetailVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const emgPlanId = ref<number>();
const levelDetailData = ref<[]>([]);
// 当前正在编辑的行索引
const editableRowIndex = ref<number>();
// 当前正在编辑的列字段
const editableColumn = ref<string>();

const queryFormRef = ref<ElFormInstance>();
const emgPlanDetailFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EmgPlanDetailForm = {
  id: undefined,
  name: undefined,
  emgPlanId: undefined,
  file: undefined,
  isEnable: undefined,
  deptInCharge: undefined,
  contacts: undefined,
  workContent: undefined,
  levelDetail: undefined
};
const data = reactive<PageData<EmgPlanDetailForm, EmgPlanDetailQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    emgPlanId: undefined,
    file: undefined,
    isEnable: undefined,
    deptInCharge: undefined,
    contacts: undefined,
    workContent: undefined,
    levelDetail: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '预案名称不能为空', trigger: 'blur' }],
    emgPlanId: [{ required: true, message: '应急预案编号不能为空', trigger: 'blur' }]
    // isEnable: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应急预案详情列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEmgPlanDetail(queryParams.value);
  emgPlanDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  emgPlanDetailFormRef.value?.resetFields();
  levelDetailData.value = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: EmgPlanDetailVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加应急预案详情';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: EmgPlanDetailVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getEmgPlanDetail(_id);
  Object.assign(form.value, res.data);
  levelDetailData.value = JSON.parse(form.value.levelDetail);
  dialog.visible = true;
  dialog.title = '修改应急预案详情';
};

/** 提交按钮 */
const submitForm = () => {
  emgPlanDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.emgPlanId = emgPlanId.value;
      if (form.value.id) {
        await updateEmgPlanDetail(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addEmgPlanDetail(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: EmgPlanDetailVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除应急预案详情编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delEmgPlanDetail(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'biz/emgPlanDetail/export',
    {
      ...queryParams.value
    },
    `emgPlanDetail_${new Date().getTime()}.xlsx`
  );
};

// 开始编辑
const startEdit = (index, column) => {
  editableRowIndex.value = index;
  editableColumn.value = column;
};

// 保存编辑
const saveEdit = (row) => {
  editableRowIndex.value = null;
  editableColumn.value = null;
  form.value.levelDetail = JSON.stringify(levelDetailData.value);
};

// 新增一行
const addRow = () => {
  if (!Array.isArray(levelDetailData.value)) {
    levelDetailData.value = [];
  }
  levelDetailData.value.push({ levelName: '', deadNum: '', injuredNum: '', economicLoss: '' }); // 插入一行空数据
  editableRowIndex.value = levelDetailData.value.length - 1; // 自动进入编辑模式
  editableColumn.value = 'levelName'; // 默认编辑第一列
};

// 删除一行
const deleteRow = (index) => {
  levelDetailData.value.splice(index, 1); // 删除指定行
  form.value.levelDetail = JSON.stringify(levelDetailData.value);
};

onMounted(() => {
  emgPlanId.value = (proxy?.$route.params as number) && (proxy?.$route.params.planId as number);
  queryParams.value.emgPlanId = emgPlanId.value;
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: 120px;
}
</style>
